package com.fili.core.serial;

import java.util.ArrayList;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Oct 19, 2006
 * Time: 10:39:20 PM
 */
public class SerialParser
{
    public static final int MSGLEN_ISPM = 12;
    public static final int MSGLEN_NORMAL = 12;
    private ArrayList<SerialConsumer> consumers;
    private StringBuffer dataBuf;


    public SerialParser()
    {
        consumers = new ArrayList<SerialConsumer>();
        dataBuf = new StringBuffer();
    }

    public void receiveData(String data)
    {
        dataBuf.append(data);
        while (true)
        {
            while ((dataBuf.length() > 0) && (dataBuf.charAt(0) != ':'))
                dataBuf.deleteCharAt(0);
            if (dataBuf.length() == 0)
                return;
            if (dataBuf.length() < MSGLEN_NORMAL)  //modify for proper length
                return;
            char c = dataBuf.charAt(1);
            if (dataBuf.charAt(2) == ';')
            {
                if ((c >= '1') && (c <= '8'))
                {
                    if (dataBuf.length() >= MSGLEN_NORMAL)
                    {
                        String s = dataBuf.substring(0, MSGLEN_NORMAL);
                        System.out.println(">>>"+s+"<<<");
                        for (SerialConsumer cons : consumers)
                        {
                            if ((cons != null) && (cons.getDataStore().getID() == (c - '1')))
                                cons.receiveData(s);
                        }

                        dataBuf.delete(0, MSGLEN_NORMAL);
                    }
                }
                else
                    if ((c >= '9') && (c <= '9' + 8))
                    {
                        if (dataBuf.length() >= MSGLEN_ISPM)
                        {
                            String s = dataBuf.substring(0, MSGLEN_ISPM);
                            System.out.println(">>>"+s+"<<<");
                            for (SerialConsumer cons : consumers)
                            {
                                if ((cons != null) && (cons.getDataStore().getID() == (c - '9')))
                                    cons.receiveData(s);
                            }

                            dataBuf.delete(0, MSGLEN_ISPM);
                        }
                    }
                    else
                        //I have some unknown stuff, discard the :
                        dataBuf.deleteCharAt(0);
            }
            else
                //I have some unknown stuff, discard the :
                dataBuf.deleteCharAt(0);
        }

    }

    public void addSerialConsumer(SerialConsumer serialConsumer)
    {
        if (consumers.indexOf(serialConsumer) < 0)
            consumers.add(serialConsumer);
    }

    public void removeSerialConsumer(SerialConsumer serialConsumer)
    {
        consumers.remove(serialConsumer);
    }
}
